package com.jbinfo.qingcaowan.wx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

/**
 * @author LiZhenWei
 *
 */
public class WxUtil {
		// 获取token URL
//	https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
		private static String GET_TOKEN_URL = CommonURL.TokenUrl;
		
		private static String appid = CommonURL.AppId;
		
		private static String appsecret = CommonURL.AppSecret;
		// 员工跳转企业网站的URL
		static String OAuth_URL = CommonURL.OAuthUrl;
		
		private static String corpid = CommonURL.CorpId;
		
		private static String corpsecret = CommonURL.CorpSecret;
		
		private static Logger logger = Logger.getLogger(WxUtil.class);
		
		private WxInfo wxInfo;

		public WxUtil(WxInfo wxInfo) {
		    this.wxInfo = wxInfo;
		}


		/**
		 * 获取AccessToken
		 * @return
		 * @throws IOException
		 */
		public WxInfo gettoken(WxInfo wxInfo) throws IOException {
			WxInfo wxDTO = new WxInfo();
			
			String url = GET_TOKEN_URL + "&appid="+appid+"&secret="+appsecret;
			URL postUrl = new URL(url);
			
			// 打开URL链接
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
			// GET方法
			connection.setRequestMethod("GET");
			
			// 
			connection.setRequestProperty("Content-Type", "application/json");
			//connection.setRequestProperty("corpid", corpid);
			//connection.setRequestProperty("corpsecret", corpsecret);

			connection.connect();

			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));

			String token;
			String strToken = "";
			String strUserId = "";
			while ((token = reader.readLine()) != null) {
				
				/*JSONObject json = JSONObject.fromObject(token);
				
				map.put("access_token", json.get("access_token").toString());
				map.put("expires_in", json.get("expires_in").toString());
				*/
				break;
			}
			System.out.println(token);
			JSONObject json = JSONObject.fromObject(token);
			wxDTO.setAccess_token(json.get("access_token").toString());
			wxDTO.setExpires_in(json.get("expires_in").toString());
			
			reader.close();
			connection.disconnect();
			
			return wxDTO;
		}
		
		/**
		 * 获取AccessToken
		 * @return
		 * @throws IOException
		 */
		public Map<String, String> getOpenId(WxInfo wxInfo) throws IOException {
			Map<String, String> map =new HashMap<String, String>();
//			String corpid = "wx1c71fc10f107d229";
//			String corpsecret = "wBiumfW0ugj5Ue7X7CRB-aNXxarJ5TVBzSCu_pR0_X9nAcbwmbBmSy1G8056YlHI";
			
			String url = GET_TOKEN_URL + "?corpid="+corpid+"&corpsecret="+corpsecret;
			try {

	           URL urlGet = new URL(url);

	           HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();

	           http.setRequestMethod("GET"); // 必须是get方式请求

	           http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

	           http.setDoOutput(true);

	           http.setDoInput(true);

	           System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒

	           System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

	           http.connect();

	           InputStream is = http.getInputStream();

	           int size = is.available();

	           byte[] jsonBytes = new byte[size];

	           is.read(jsonBytes);

	           String message = new String(jsonBytes, "UTF-8");
	           
	           JSONObject demoJson=JSONObject.fromObject(message);

	           String accessToken = demoJson.getString("access_token");
	           
	           String openid = demoJson.getString("openid");
	           
	           wxInfo.setAccess_token(accessToken);
	           //accessTokenInfo.setGenTime(new Date());
	           
	          /* if (StringUtils.isBlank(code)) {
	        	   System.out.println("-------------往全局变量里存accessToken--------------"+accessTokenInfo.getAccessToken());
	        	   map.put("wxInfo", wxInfo);
	           }*/
	           
	           is.close();

	       } catch (Exception e) {

	           e.printStackTrace();

	       }
			
			return map;
	  
		}
}
